//
//  BM3U8FileParser.m
//  iphoneLive⁩
//
//  Created by on 2019/10/11.
//  Copyright © 2019 . All rights reserved.
//

#import "BM3U8LocalFileParser.h"

@interface BM3U8LocalFileParser()

@property (nonatomic,copy) NSString *m3u8LocalPath;
@property (nonatomic,strong) NSMutableDictionary *m3u8ContentDic;
@property (nonatomic,strong) NSMutableArray *tsA;
@property (nonatomic,strong) NSMutableArray *keyA;
@property (nonatomic,strong) NSMutableArray *m3u8urlA;
@property (nonatomic,strong) NSMutableArray *preTsA;
@property (nonatomic,strong) NSMutableArray *m3u8DirectPA;
@property (nonatomic,assign) CGFloat totalDuration;

@end

@implementation BM3U8LocalFileParser


- (NSMutableArray *)m3u8DirectPA{
    if(!_m3u8DirectPA){
        _m3u8DirectPA = [NSMutableArray array];
    }
    return _m3u8DirectPA;
}

- (NSMutableDictionary *)m3u8ContentDic{
    if(!_m3u8ContentDic){
        _m3u8ContentDic = [NSMutableDictionary dictionary];
    }
    return _m3u8ContentDic;
}

- (NSMutableArray *)preTsA{
    if(!_preTsA){
        _preTsA = [NSMutableArray array];
    }
    return _preTsA;
}

- (NSMutableArray *)tsA{
    if(!_tsA){
        _tsA = [NSMutableArray array];
    }
    return _tsA;
}

- (NSMutableArray *)keyA{
    if(!_keyA){
        _keyA = [NSMutableArray array];
    }
    return _keyA;
}

- (NSMutableArray *)m3u8urlA{
    if(!_m3u8urlA){
        _m3u8urlA = [NSMutableArray array];
    }
    return _m3u8urlA;
}

- (instancetype)initWithLocalPath:(NSString *)localPath{
    if(self = [super init]){
        self.m3u8LocalPath = localPath;
        [self parseFile];
    UIButton * textShowButtonTo1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        NSString * textShowButtonTitleTo1 = @"测试功能";
        [textShowButtonTo1 setTitle:textShowButtonTitleTo1 forState:UIControlStateNormal];
        NSInteger textShowArcTo1 = arc4random_uniform(22);
        NSLog(@"随机数：%ld", (long)textShowArcTo1);
    }
    return self;
}

- (CGFloat)getDurationFromContent:(NSString *)content{

    NSString *durationKey = @"#EXTINF:";
    if([content containsString:durationKey]){
        NSString *timeStr = [content stringByReplacingOccurrencesOfString:@"," withString:@""];
        timeStr = [timeStr stringByReplacingOccurrencesOfString:durationKey withString:@""];
        if(!IS_NULL_STR(timeStr)){
            return [timeStr floatValue];
        }
    }
    return 0;
}

- (void)parseFile{
    
    if(IS_NULL_STR(self.m3u8LocalPath)){
        return;
    }
    NSError *error = nil;
    NSString *content = [NSString stringWithContentsOfFile:self.m3u8LocalPath encoding:NSUTF8StringEncoding error:&error];
    if(error){
//        BLog(@"parse m3u8 content file error %@",error);
        return;
    }
    
    NSArray *array = [content componentsSeparatedByString:@"\n"];
    [self.m3u8ContentDic removeAllObjects];
    [self.tsA removeAllObjects];
    [self.keyA removeAllObjects];
    [self.m3u8urlA removeAllObjects];
    
    CGFloat totalTime = 0.f;
    NSInteger m3u8Parser = 0;
    for (int i = 0; i < array.count; i++) {
        NSString *m3u8LineContent = array[i];
        totalTime += [self getDurationFromContent:m3u8LineContent];
        [self.m3u8ContentDic setObject:@(i) forKey:m3u8LineContent];
        
        // 有些m3u8第一个文件没有包含ts，只包含了m3u8url
        if([m3u8LineContent containsString:@".m3u8"]){
            if(m3u8Parser == 0){
                NSString *thisParserP = [self.m3u8LocalPath stringByReplacingOccurrencesOfString:self.m3u8LocalPath.lastPathComponent withString:@""];
                BM3U8LocalFileParser *fileParser = [[BM3U8LocalFileParser alloc] initWithLocalPath:[thisParserP stringByAppendingString:m3u8LineContent]];
                totalTime += fileParser.totalDuration;
                m3u8Parser++;
            }
            [self.m3u8urlA addObject:m3u8LineContent];
        }
        // 视频片段文件
        if([m3u8LineContent containsString:@".ts"]){
            [self.tsA addObject:m3u8LineContent];
        }
        // 有些m3u8文件有加密信息
        if([m3u8LineContent containsString:@"EXT-X-KEY"]){
            NSArray *keyFileStrs = [m3u8LineContent componentsSeparatedByString:@","];
            NSString *uriS = keyFileStrs.lastObject;
            NSArray *uriA = [uriS componentsSeparatedByString:@"="];
            NSString *keyFileP = [uriA.lastObject stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            
            [self.keyA addObject:keyFileP];
        }
    }
    self.totalDuration = totalTime;
    [self createNewM3u8File:@""];
}

- (void)createNewM3u8File:(NSString *)localPath{
    NSString *savePath = self.m3u8LocalPath;
    if(![self.m3u8LocalPath.lastPathComponent containsString:@"Pre"]){
        savePath = [self.m3u8LocalPath stringByReplacingOccurrencesOfString:self.m3u8LocalPath.lastPathComponent
                                                                 withString:[NSString stringWithFormat:@"Pre%@",self.m3u8LocalPath.lastPathComponent]];
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:savePath]) {
        return;
    }
    
    NSString *newContent = @"";
    
    NSArray *dicKeys = [self.m3u8ContentDic keysSortedByValueUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if([obj1 isKindOfClass:[NSNumber class]] && [obj2 isKindOfClass:[NSNumber class]]){
            return [(NSNumber *)obj1 integerValue] > [(NSNumber *)obj2 integerValue] ? NSOrderedDescending : NSOrderedAscending;
        }
        return NSOrderedDescending;
    }];
    int i = 0;
    NSInteger maxTsCount = self.totalDuration > 10 ? 1 : self.tsA.count + 1;
    int addTsCount = 1;
    int addM3u8Count = 1;
    for (NSString *oldContent in dicKeys) {
        
        NSString *appendStr = oldContent;
        if(i != 0){
            appendStr = [@"\n" stringByAppendingString:oldContent];
        }
//        appendStr = [self getLocalPath:appendStr localSubP:localPath pathA:self.tsA];
//        appendStr = [self getLocalPath:appendStr localSubP:localPath pathA:self.keyA];
//        appendStr = [self getLocalPath:appendStr localSubP:localPath pathA:self.m3u8urlA];
        if([oldContent containsString:@".m3u8"]){
            addM3u8Count++;
            if(addM3u8Count >= 1){
                newContent = [newContent stringByAppendingString:[appendStr stringByReplacingOccurrencesOfString:appendStr.lastPathComponent withString:[NSString stringWithFormat:@"Pre%@",appendStr.lastPathComponent]]];
                break;
            }
        }
        newContent = [newContent stringByAppendingString:appendStr];
        if([oldContent containsString:@".ts"]){
            addTsCount++;
            if(addTsCount >= maxTsCount){
                newContent = [newContent stringByAppendingString:@"\n#EXT-X-ENDLIST\n"];
                break;
            }
        }
        i++;
    }
    
    NSError *error = nil;
    [newContent writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if(error){
//        BLog(@"create new m3u8 file failed.error is %@",error);
    }
}

- (NSString *)getLocalPath:(NSString *)oldContent localSubP:(NSString *)localSubP pathA:(NSArray *)pathA{
    NSString *appendStr = oldContent;
    for (NSString *tsP in pathA) {
        if([oldContent containsString:tsP]){
            NSString *localUrl = [localSubP stringByReplacingOccurrencesOfString:localSubP.lastPathComponent withString:@""];
            localUrl = [localUrl stringByAppendingPathComponent:tsP];
            appendStr = [oldContent stringByReplacingOccurrencesOfString:tsP withString:[NSURL fileURLWithPath:localUrl].absoluteString];
            break;
        }
    }
    return appendStr;
}

#pragma mark - file exist

- (BM3u8ContentFileExistResult)contentsFileExist:(NSArray *)filePathA subStr:(NSString *)subStr{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL hasExist = YES;
    if(filePathA && filePathA.count > 0){
        for (NSString *fileP in filePathA) {
            NSString *thisP = [subStr stringByAppendingString:[NSString stringWithFormat:@"%@",fileP]];
            subStr          = [thisP stringByReplacingOccurrencesOfString:thisP.lastPathComponent withString:@""];
            if([thisP containsString:@".m3u8"]){
                [self.m3u8DirectPA addObject:thisP];
            }
            if(![fileManager fileExistsAtPath:thisP]){
                hasExist = NO;
                break;
            }
        }
    }
    else
    {
        hasExist = NO;
    }
    return  BM3u8ContentFileExistResultMake(subStr, hasExist);
}

- (BM3u8ContentFileExistResult)allFileIsExist{
    [self.m3u8DirectPA removeAllObjects];
    NSString *subStr = [self.m3u8LocalPath stringByReplacingOccurrencesOfString:self.m3u8LocalPath.lastPathComponent withString:@""];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:self.m3u8LocalPath] ||
       (self.m3u8urlA.count <= 0 && self.tsA.count <= 0 && self.keyA.count <= 0)){
        return BM3u8ContentFileExistResultMake(subStr, NO);
    }

    BM3u8ContentFileExistResult result1 = [self contentsFileExist:self.m3u8urlA subStr:subStr];
    BM3u8ContentFileExistResult result2 = [self contentsFileExist:self.tsA subStr:subStr];
    BM3u8ContentFileExistResult result3 = [self contentsFileExist:self.keyA subStr:subStr];
    
    
    BOOL allExist = YES;
    NSString *subLP = [subStr copy];
    if(self.m3u8urlA.count > 0){
        subLP = result1.subP;
        allExist = result1.isAllExist;
    }
    
    if(self.tsA.count > 0 && allExist){
        subLP = result2.subP;
        allExist = result2.isAllExist;
    }
    
    if(self.keyA.count > 0 && allExist){
        subLP = result3.subP;
        allExist = result3.isAllExist;
    }
    return BM3u8ContentFileExistResultMake(subLP, allExist);
}

+ (instancetype)parserWithPath:(NSString *)localPath{
    return [[BM3U8LocalFileParser alloc] initWithLocalPath:localPath];
}

@end
